package com.lx.algorithm.code.xly3.class04;

import com.lx.algorithm.Utils;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2022-01-12 15:20:18
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2022-01-12     张李鑫                     1.0         1.0 Version
 */
public class Code06 {
    /**
     * 给定一个数组arr，返回子数组的最大累加和。
     * 每次进来都累加 并捕捉更新最大值 如果小于0了就从下一个开始重新计算
     */
    public static int maxSum(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        int sum = 0;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
            max = Math.max(sum, max);
            sum = Math.max(sum, 0);
        }
        return max;
    }

    public static int maxSumII(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        int max = Integer.MIN_VALUE;
        int cur = 0;
        for (int i = 0; i < arr.length; i++) {
            cur += arr[i];
            max = Math.max(max, cur);
            cur = cur < 0 ? 0 : cur;
        }
        return max;
    }

    public static void main(String[] args) {
        int size = 1000;
        for (int i = 0; i < 1000; i++) {
            int[] ints = Utils.generateRandomMatrixII(size);

            if (maxSum(ints) !=
                    maxSumII(ints)) {
                System.out.println("error");
                break;
            }
        }
    }

}
